package com.www.applyword.main;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.LoginBean;
import com.www.applyword.bean.ParamsBean;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.ui.my.ResetPasswordActivity;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author : huang
 * date   : 2019/10/26 0026 9:23
 * version: 1.0
 */
    public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.sb_login)
    SuperButton sbLogin;
    @BindView(R.id.tv_registered)
    TextView tvRegistered;
    @BindView(R.id.tv_forget_password)
    TextView tv_forget_password;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.sb_code)
    SuperButton sbCode;
    private VerificationCodeCountTimer verificationCodeCountTimer;

    @Override
    protected void loadViewLayout() {
       // initView();
        setContentView(R.layout.login_activity);
        setTitle("登录");
        ib_back.setVisibility(View.INVISIBLE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        verificationCodeCountTimer = new VerificationCodeCountTimer(61100, 1000);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.REGISTER) ) {
               finish();
            }
        }
    }

    class VerificationCodeCountTimer extends CountDownTimer {

        private VerificationCodeCountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            int time = (int) (Math.round((double) millisUntilFinished / 1000) - 1);
            // sbCode.setTextColor(getResources().getColor(R.color.color_yellow2));
            sbCode.setText(time + "s");
        }

        @Override
        public void onFinish() {
            sbCode.setText("获取验证码");
        }
    }


    private void initView() {
        if (SPUtil.getBoolean("login") && !TextUtils.isEmpty(SPUtil.getString(Constants.PHONE))){
            TIMManager.getInstance().autoLogin(SPUtil.getString(Constants.PHONE), new TIMCallBack() {
                @Override
                public void onError(int errCode, String errMsg) {
                    //  Utils.showToastSafe("login failed. code: " + errCode + " -------errmsg: " + errMsg);
                    if (errCode == 6026){
                        TUIKit.login(SPUtil.getString(Constants.PHONE),SPUtil.getString(Constants.USERSIG), new IUIKitCallBack() {
                            @Override
                            public void onSuccess(Object data) {
                                SPUtil.put("login", true);
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            }

                            @Override
                            public void onError(String module, int errCode, String errMsg) {
                                //错误码 code 和错误描述 desc，可用于定位请求失败原因
                                //错误码 code 列表请参见错误码表
                                Log.d(Constants.TAG, "login failed. code: " + errCode + " errmsg: " + errMsg);
                               // Utils.showToastSafe("login failed. code: " + errCode + " -------errmsg: " + errMsg);
                            }
                        });
                    }
                }

                @Override
                public void onSuccess() {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }
            });
            return;
        }
    }

    @Override
    protected void loadData() {

    }


    @OnClick({R.id.sb_login, R.id.tv_registered,R.id.tv_forget_password,R.id.sb_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sb_login:
                if (!Utils.isPhoneNumber(etPhone.getText().toString())){
                Utils.showToastSafe("请输入正确的手机号码");
                return;
            }
                if (TextUtils.isEmpty(etPassword.getText().toString())){
                Utils.showToastSafe("请输入密码");
                return;
               }
                if (Utils.isFastClick())
                login2();
                break;
            case R.id.tv_registered:
                startActivity(new Intent(this,RegisterActivity.class));
                break;
                //忘记密码
            case R.id.tv_forget_password:
                startActivity(new Intent(this, ResetPasswordActivity.class).putExtra("type", 1));
                break;
            case R.id.sb_code:
                getCode();
                break;
                default:
        }
    }

    private void login2() {
        Map<String, Object> params = new HashMap<>();
        params.put("Mobile",etPhone.getText().toString());
        params.put("Pwd",etPassword.getText().toString());
        HttpClient.get(LoginActivity.this,Constants.LOGIN,params , new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                String userSig = result.getUserSig();
                SPUtil.put(Constants.USERID,result.getUser().getUserInfo_ID());
                SPUtil.put(Constants.USERSIG,userSig);
                SPUtil.put(Constants.PHONE,result.getUser().getUserInfo_Mobile());
                SPUtil.put("login", true);
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();

               /* TUIKit.login(result.getUser().getUserInfo_Mobile(),userSig, new IUIKitCallBack() {
                    @Override
                    public void onSuccess(Object data) {
                        SPUtil.put("login", true);
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onError(String module, int errCode, String errMsg) {
                        //错误码 code 和错误描述 desc，可用于定位请求失败原因
                        //错误码 code 列表请参见错误码表
                        Log.d(Constants.TAG, "login failed. code: " + errCode + " errmsg: " + errMsg);
                        //    Utils.showToastSafe("login failed. code: " + errCode + " -------errmsg: " + errMsg);
                        if (errCode == 7501){
                            TUIKit.login(result.getUser().getUserInfo_Mobile(),userSig, new IUIKitCallBack() {
                                @Override
                                public void onSuccess(Object data) {
                                    SPUtil.put("login", true);
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                }

                                @Override
                                public void onError(String module, int errCode, String errMsg) {
                                    //错误码 code 和错误描述 desc，可用于定位请求失败原因
                                    //错误码 code 列表请参见错误码表
                                    Log.d(Constants.TAG, "login failed. code: " + errCode + " errmsg: " + errMsg);
                                    //   Utils.showToastSafe("login failed. code: " + errCode + " -------errmsg: " + errMsg);
                                }
                            });
                        }
                    }
                });*/
            }
        });
    }

    private void getCode() {
        if (!Utils.isPhoneNumber(etPhone.getText().toString())) {
            Utils.showToastSafe("请输入正确的手机号码");
            return;
        }
        verificationCodeCountTimer.start();
        Map<String, Object> params = new HashMap<>();
        ParamsBean paramsBean = new ParamsBean();
        params.put("mobile", etPhone.getText().toString());
        params.put("appKey", paramsBean.getAppKey());
        params.put("townId", paramsBean.getTownId());
        params.put("version", paramsBean.getVersion());
        params.put("versionCode", paramsBean.getVersionCode());
        params.put("channel", paramsBean.getChannel());
        params.put("downloadSource", paramsBean.getDownloadSource());
        params.put("deviceId", paramsBean.getDeviceId());
        params.put("osVersionName", paramsBean.getOsVersionName());
        params.put("timestamp", paramsBean.getTimestamp());
        params.put("sign", paramsBean.getSign());
        params.put("model", paramsBean.getModel());
        params.put("brand", paramsBean.getBrand());
        params.put("product", paramsBean.getProduct());
        params.put("sdkversion", paramsBean.getSdkversion());
        params.put("imei", paramsBean.getImei());
        params.put("androidid", paramsBean.getAndroidid());
        HttpClient.post(LoginActivity.this, Constants.verifyCode, params, new CallBack<String>() {
            @Override
            public void onSuccess(String result) {
                // etCode.setText(result);
            }
        });
    }

    private void login() {
        Map<String, Object> params = new HashMap<>();
        ParamsBean paramsBean = new ParamsBean();
        params.put("mobile",etPhone.getText().toString().trim());
        params.put("password",etPassword.getText().toString().trim());
        params.put("appKey", paramsBean.getAppKey());
        params.put("townId", paramsBean.getTownId());
        params.put("version", paramsBean.getVersion());
        params.put("versionCode", paramsBean.getVersionCode());
        params.put("channel", paramsBean.getChannel());
        params.put("downloadSource", paramsBean.getDownloadSource());
        params.put("deviceId", paramsBean.getDeviceId());
        params.put("osVersionName", paramsBean.getOsVersionName());
        params.put("timestamp", paramsBean.getTimestamp());
        params.put("sign", paramsBean.getSign());
        params.put("model", paramsBean.getModel());
        params.put("brand", paramsBean.getBrand());
        params.put("product", paramsBean.getProduct());
        params.put("sdkversion", paramsBean.getSdkversion());
        params.put("imei", paramsBean.getImei());
        params.put("androidid", paramsBean.getAndroidid());
        params.put("lon", paramsBean.getLon());
        params.put("lat", paramsBean.getLat());
        params.put("oaid", paramsBean.getOaid());
        HttpClient.get(LoginActivity.this,Constants.login,params , new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
               // String userSig = result.getUserSig();
                SPUtil.put(Constants.USERID2,result.userId);
                SPUtil.put(Constants.PHOTO2,result.CustomerServicePhone);
                SPUtil.put(Constants.PHONE2,result.mobile);
                SPUtil.put(Constants.TOKEN,result.token);
                SPUtil.put("login", true);
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();


               /* TUIKit.login(result.getUser().getUserInfo_Mobile(),userSig, new IUIKitCallBack() {
                    @Override
                    public void onSuccess(Object data) {
                        SPUtil.put("login", true);
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onError(String module, int errCode, String errMsg) {
                        //错误码 code 和错误描述 desc，可用于定位请求失败原因
                        //错误码 code 列表请参见错误码表
                        Log.d(Constants.TAG, "login failed. code: " + errCode + " errmsg: " + errMsg);
                    //    Utils.showToastSafe("login failed. code: " + errCode + " -------errmsg: " + errMsg);
                        if (errCode == 7501){
                            TUIKit.login(result.getUser().getUserInfo_Mobile(),userSig, new IUIKitCallBack() {
                                @Override
                                public void onSuccess(Object data) {
                                    SPUtil.put("login", true);
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                }

                                @Override
                                public void onError(String module, int errCode, String errMsg) {
                                    //错误码 code 和错误描述 desc，可用于定位请求失败原因
                                    //错误码 code 列表请参见错误码表
                                    Log.d(Constants.TAG, "login failed. code: " + errCode + " errmsg: " + errMsg);
                                 //   Utils.showToastSafe("login failed. code: " + errCode + " -------errmsg: " + errMsg);
                                }
                            });
                        }
                    }
                });*/
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (verificationCodeCountTimer != null) {
            verificationCodeCountTimer.cancel();
        }
    }
}
